#pragma once

#include <iostream>
#include <string>
#include <memory>
#include <vector>

#include <sys/epoll.h>
#include "Socket.hpp"

class EpollServer
{
    static const int gnum = 64;
    static const int TIMROUT = 1000;
public:
    EpollServer(uint16_t port)
        :_port(port)
        ,_sock(std::make_unique<sock::TcpSocket>("0.0.0.0", port))
    {
        _sock->CreateSocket();
        _sock->BindSocket();
        _sock->Listen();

        // 创建epoll模型, size 已经被取代了
        _epfd = epoll_create(128);
        if(_epfd < 0)
        {
            LOG(FATAL, "epoll_create fail\n");
        }

        // 添加进红黑树
        epoll_event ev;
        ev.events |= EPOLLIN;
        ev.data.fd = _sock->GetSockfd();
        epoll_ctl(_epfd, EPOLL_CTL_ADD, _sock->GetSockfd(), &ev);
    }

    ~EpollServer()
    {
        _sock->Close();
        close(_epfd);
    }

    void AcceptClient()
    {
        sockaddr_in client_addr;
        socklen_t len = sizeof(client_addr);
        int newfd = _sock->Accept(&client_addr, &len);

        InetAddr cli_addr(client_addr);
        LOG(INFO, "接收到新链接 %d: %s:%d\n", newfd, cli_addr.getip().c_str(), cli_addr.getport());

        epoll_event ev;
        ev.events |= EPOLLIN;
        ev.data.fd = newfd;
        epoll_ctl(_epfd, EPOLL_CTL_ADD, newfd, &ev);
    }

    void Service(int fd)
    {
        char buffer[1024];
        ssize_t n = read(fd, buffer, sizeof(buffer) - 1);
        if(n > 0)
        {
            buffer[n] = '\0';
            std::string echo_str = "[server echo]# ";
            echo_str += buffer;
            LOG(INFO, "get a new message: %s\n", echo_str.c_str());
            send(fd, echo_str.c_str(), echo_str.size(), 0);
        }
        else if(n == 0)
        {
            // 要先从epoll中删除fd，才能close，不然epoll中的删除就是非法的
            epoll_ctl(_epfd, EPOLL_CTL_DEL, fd, nullptr);
            close(fd);
        }
        else
        {
            LOG(ERROR, "read error\n");
            // 要先从epoll中删除fd，才能close，不然epoll中的删除就是非法的
            epoll_ctl(_epfd, EPOLL_CTL_DEL, fd, nullptr);
            close(fd);
        }
    }

    // 处理 n 个事件
    void HandleEvent(int n)
    {
        for(int i = 0; i < n; ++i)
        {
            uint32_t event = _revs[i].events;
            int fd = _revs[i].data.fd;

            if(event & EPOLLIN)
            {
                if(fd == _sock->GetSockfd())
                {
                    // 新用户到来
                    AcceptClient();
                }
                else 
                {
                    // 用户发来的消息
                    Service(fd);
                }
            }
        }
    }

    void Loop()
    {
        while(true)
        {
            int n = epoll_wait(_epfd, _revs, gnum, TIMROUT);
            
            if(n == 0)
            {
                LOG(INFO, "超时...\n");
            }
            else if(n > 0)
            {
                LOG(INFO, "事件就绪...");
                HandleEvent(n);
            }
            else 
            {
                LOG(ERROR, "epoll_wait 出错...\n");
            }
        }
    }
private:
    uint16_t _port;
    std::unique_ptr<sock::TcpSocket> _sock;
    int _epfd;

    epoll_event _revs[gnum];
};